package cn.kgc.springboot.config;

import cn.kgc.springboot.shiro.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sun.security.krb5.Realm;

import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/8/10
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 设置登录页地址
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        // 配置受限资源
        HashMap<String, String> map = new HashMap<>();
        // anon 设置资源允许匿名访问
        map.put("/register.html", "anon");
        map.put("/user/login", "anon");
        map.put("/user/register", "anon");
        // authc   资源受限  通过认证才能访问
        map.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customerRealm());
        return  defaultWebSecurityManager;

    }

    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //创建凭证匹配器对象
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(md5);
        return  customerRealm;
    }

}
